Skip to content

Cast federation payload explicilty to an object #686

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 4 commits into
base: main
Choose a base branch
from

Conversation

thijskuilman
Copy link

@thijskuilman thijskuilman commented Oct 4, 2024

Pull Request

Related issue

Fixes #685

What does this PR do?

  • It casts the federation payload explicitly to an object. This solves the error that appears when no MultiSearchFederation properties have been set.

PR checklist

Please check if your PR fulfills the following requirements:

  • Does this PR fix an existing issue, or have you listed the changes applied in the PR description (and why they are needed)?
  • Have you read the contributing guidelines?
  • Have you made sure that the title is accurate and descriptive of the changes?

Summary by CodeRabbit

  • Bug Fixes

    • Improved handling of empty federation data in multi-search requests to prevent unexpected errors.
  • Tests

    • Added a test to ensure that submitting an empty federation in a multi-search does not cause exceptions.

@norkunas
Copy link
Collaborator

norkunas commented Oct 4, 2024

Please add test then to avoid regressions in future

Copy link

codecov bot commented Oct 4, 2024

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 89.78%. Comparing base (368c73f) to head (4d6c355).
Report is 73 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main     #686      +/-   ##
==========================================
- Coverage   90.74%   89.78%   -0.97%     
==========================================
  Files          52       59       +7     
  Lines        1340     1449     +109     
==========================================
+ Hits         1216     1301      +85     
- Misses        124      148      +24     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

Copy link
Member

@curquiza curquiza left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@thijskuilman

thank you for your PR ❤️

I agree with norkunas, can you add a test with an empty MultiSearchFederation to ensure it works all the time?

@curquiza curquiza added the bug Something isn't working label Oct 4, 2024
…hen you pass an empty MultiSearchFederation to the multiSearch function
…hen you pass an empty MultiSearchFederation to the multiSearch function
@thijskuilman
Copy link
Author

@norkunas @curquiza I have added a test!

@norkunas
Copy link
Collaborator

@thijskuilman not sure that we need a functional test here :) better would be to assert on that what was really passed to http client, because now a test without assertions doesn't prove anything

@norkunas
Copy link
Collaborator

norkunas commented Oct 11, 2024

IMHO we should a dev requirement for symfony/http-client, which allows easier testing than the guzzle.

Then your test could look like this:

$mockHttpClient = new \Symfony\Component\HttpClient\MockHttpClient(static function (string $method, string $url, array $options) {
    // assert on method, url, options['body'] or whatever what was passed

    return new JsonMockResponse([]);
});
$httpClient = new \Symfony\Component\HttpClient\Psr18Client($mockHttpClient);

$meilisearch = new \Meilisearch\Client('http://meilisearch', 'api_key', $httpClient);
$meilisearch->multiSearch([], new MultiSearchFederation());

code is just an idea and is not validated :)

@thijskuilman
Copy link
Author

thijskuilman commented Oct 11, 2024

better would be to assert on that what was really passed to http client, because now a test without assertions doesn't prove anything

Yeah, I agree that it seems a bit weird that no assertions are done in the test. However, the current test does prove that no exceptions are raised during the function call: if you'd revert the object casting, then the test fails because the ApiException is thrown. I could make the test more specific by wrapping it in a try catch and check specifically on ApiException if that's more desirable.

Beside that: I agree that testing the HTTP client instead might be nice (or a better solution) as well! :)

@norkunas
Copy link
Collaborator

My point was that unit test will be faster than the functional one :)

@@ -25,7 +25,7 @@ public function multiSearch(array $queries = [], ?MultiSearchFederation $federat

$payload = ['queries' => $body];
if (null !== $federation) {
$payload['federation'] = $federation->toArray();
$payload['federation'] = (object) $federation->toArray();

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why is typecasting necessary? You could use $payload['federation'] = $federation; and it would work just fine.

@ruhulfbr
Copy link

@curquiza Could you please review and process this PR or provide a solution? This is an important update.

@curquiza curquiza requested a review from Strift January 15, 2025 08:44
@curquiza
Copy link
Member

Hello @ruhulfbr
we have a lot on our plate now, but @Strift will review your PR when he will have more time for this
In the meantime if you have time @norkunas, you can review and merge of course. If you cannot, no worries, we will take care of it later

@norkunas
Copy link
Collaborator

norkunas commented Jan 23, 2025

I've already reviewed and my point still stands - it'd enough for unit test (current test does not do any assertion)

Copy link

coderabbitai bot commented May 29, 2025

Walkthrough

The change updates how the 'federation' key is constructed in the payload for the multiSearch method, casting its value to an object instead of an array. Additionally, a new test verifies that passing an empty MultiSearchFederation object to multiSearch does not cause an exception.

Changes

File(s) Change Summary
src/Endpoints/Delegates/HandlesMultiSearch.php Casts the 'federation' array to an object before including it in the multiSearch payload.
tests/Endpoints/HandlesMultiSearchTest.php Adds a test ensuring that an empty MultiSearchFederation does not cause exceptions in use.

Assessment against linked issues

Objective Addressed Explanation
Ensure federated multi-search works when passing an empty MultiSearchFederation object (#685)

Poem

In the warren of code, a bug did appear,
Empty federations brought developers fear.
Now cast as an object, the error is gone,
Multi-search hops smoothly, the tests carry on!
With every new fix, our spirits take flight—
🐇✨ Code rabbits rejoice, all through the night!

✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 2a5bef7 and 4d6c355.

📒 Files selected for processing (2)
  • src/Endpoints/Delegates/HandlesMultiSearch.php (1 hunks)
  • tests/Endpoints/HandlesMultiSearchTest.php (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
tests/Endpoints/HandlesMultiSearchTest.php (4)
src/Contracts/MultiSearchFederation.php (1)
  • MultiSearchFederation (7-94)
src/Contracts/SearchQuery.php (2)
  • SearchQuery (7-495)
  • setIndexUid (365-370)
tests/TestCase.php (3)
  • TestCase (16-180)
  • createEmptyIndex (139-145)
  • safeIndexName (147-150)
src/Endpoints/Delegates/HandlesMultiSearch.php (1)
  • multiSearch (18-32)
⏰ Context from checks skipped due to timeout of 90000ms (4)
  • GitHub Check: integration-tests (PHP 8.4) (Kriswallsmith-Buzz)
  • GitHub Check: integration-tests (PHP 8.4) (Guzzle-7-Adapter)
  • GitHub Check: integration-tests (PHP 8.1) (PHP-HTTP-CurlClient)
  • GitHub Check: integration-tests (PHP 8.0) (Kriswallsmith-Buzz)
🔇 Additional comments (1)
src/Endpoints/Delegates/HandlesMultiSearch.php (1)

28-28: Object casting is necessary for proper API compatibility.

The explicit casting to (object) is required because when MultiSearchFederation has no properties set, $federation->toArray() returns an empty array [] due to the array_filter() call in the toArray() method. However, the Meilisearch API expects an object structure {} rather than an array [] for the federation parameter.

Without the cast, JSON encoding would produce:

{"queries": [...], "federation": []}

With the cast, it correctly produces:

{"queries": [...], "federation": {}}

This addresses the root cause mentioned in issue #685.

Responding to the past review comment: Direct assignment $payload['federation'] = $federation; would not work because we need the array representation from toArray(), but cast as an object for proper JSON serialization.

Comment on lines +24 to +34
public function testPassingEmptyMultiSearchFederationDoesNotCauseException(): void
{
$this->expectNotToPerformAssertions();

$this->client->multiSearch([
(new SearchQuery())->setIndexUid($this->firstIndex->getUid()),
(new SearchQuery())->setIndexUid($this->secondIndex->getUid()),
],
new MultiSearchFederation()
);
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Consider implementing unit tests with HTTP client assertions.

While this test ensures no exceptions are thrown, it lacks assertions on the actual behavior and uses a functional testing approach. As discussed in the PR comments, a more robust approach would be to unit test the HTTP client interactions directly.

Consider implementing the suggestion from the PR comments to mock the HTTP client and assert on the request payload:

public function testEmptyFederationPayloadIsCastToObject(): void
{
    $httpClient = $this->createMock(Http::class);
    $httpClient->expects($this->once())
        ->method('post')
        ->with(
            '/multi-search',
            $this->callback(function ($payload) {
                // Verify federation is an object (stdClass) not an array
                return isset($payload['federation']) 
                    && $payload['federation'] instanceof \stdClass;
            })
        );
    
    $client = new Client('http://localhost:7700');
    // Inject mocked HTTP client...
    
    $client->multiSearch(
        [(new SearchQuery())->setIndexUid('test')],
        new MultiSearchFederation()
    );
}

This approach would:

  • Verify the actual payload structure sent to the API
  • Run faster as a unit test
  • Provide more reliable regression protection

Would you like me to help implement a more comprehensive unit testing approach for this functionality?

🤖 Prompt for AI Agents
In tests/Endpoints/HandlesMultiSearchTest.php around lines 24 to 34, the current
test only checks that no exceptions occur but does not verify the actual HTTP
request payload. To improve, mock the HTTP client used by the multiSearch
method, set an expectation that the post method is called once with a payload
where the federation field is an object (stdClass), not an array. Then inject
this mocked client into the Client instance and call multiSearch with an empty
MultiSearchFederation. This will unit test the HTTP interaction and payload
structure more robustly.


public function testPassingEmptyMultiSearchFederationDoesNotCauseException(): void
{
$this->expectNotToPerformAssertions();
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Remove expectNotToPerformAssertions() and add meaningful assertions.

The expectNotToPerformAssertions() call indicates this test isn't actually verifying the fix works correctly - only that it doesn't throw exceptions. This makes the test less valuable for preventing regressions.

At minimum, consider adding an assertion that verifies the method completes successfully:

-    $this->expectNotToPerformAssertions();
-
-    $this->client->multiSearch([
+    $result = $this->client->multiSearch([
         (new SearchQuery())->setIndexUid($this->firstIndex->getUid()),
         (new SearchQuery())->setIndexUid($this->secondIndex->getUid()),
     ],
         new MultiSearchFederation()
     );
+    
+    $this->assertIsArray($result);
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
$this->expectNotToPerformAssertions();
$result = $this->client->multiSearch([
(new SearchQuery())->setIndexUid($this->firstIndex->getUid()),
(new SearchQuery())->setIndexUid($this->secondIndex->getUid()),
],
new MultiSearchFederation()
);
$this->assertIsArray($result);
🤖 Prompt for AI Agents
In tests/Endpoints/HandlesMultiSearchTest.php at line 26, remove the call to
expectNotToPerformAssertions() because it prevents the test from verifying
actual outcomes. Instead, add meaningful assertions that confirm the method
under test behaves as expected, such as checking the returned data structure,
status codes, or specific values to ensure the fix works correctly and prevent
regressions.

@Strift Strift added the stale Pull request or issue that has recieve no activity for a long time. label May 29, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working stale Pull request or issue that has recieve no activity for a long time.
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Federated multi-search example does not work
5 participants